<?php
namespace Api;

use Kuyuan\WqCore\api\Api;
use Kuyuan\WqCore\util\File;
use Kuyuan\WqCore\util\Util;

/**
 * 红包海报
 * Class Poster
 * @package Api
 */
class Poster extends Api
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取前端合成海报所需数据
     */
    public function getPsPoster()
    {
        Util::appointGet();
        //红包标题、昵称、头像、红包二维码
        $Red = $this->newController("Red");
        $_red = $Red->getHomeOne($this->_gpc["red_id"]);
        $Share = $this->newController("Share");
        $_share_id = $Share->add($this->_gpc["red_id"]);
        $_url = murl('entry//mobile',array('m'=>KUYUAN_NAME,'share_id'=>$_share_id),true,true);
        $_data = array(
            "title" => $_red["title"],
            "nickname" => $_red["owner_nickname"],
            "header" => KUYUAN_DEBUG ? 'https://file.geekdm.com/test-header.jpg' : $this->wxHeaderToLocation($_red["owner_header"],$_red["uid"]),
            "qrcode" => KUYUAN_DEBUG ? 'https://file.geekdm.com/test-qrcode.png' : $Red->getRedQrcode($this->_gpc["red_id"],$_url)
        );
        $_result = array("code"=>0,"data"=>$_data);
        unset($_red,$Red,$Share,$_data);
        Util::returns($_result);
    }

    /**
     * 将微信头像拉取到本地
     * @param $_url
     * @param $_uid
     * @return mixed
     */
    private function wxHeaderToLocation($_url,$_uid)
    {
        load()->func('file');
        $_dir = File::dir("header");

        $_filename = strstr($_dir.$_uid.".jpg",KUYUAN_NAME);
        if(!is_file($_filename)){
            $hander = curl_init();
            curl_setopt($hander,CURLOPT_URL,$_url);
            curl_setopt($hander, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($hander,CURLOPT_HEADER,0);
            curl_setopt($hander,CURLOPT_FOLLOWLOCATION,1);
            curl_setopt($hander,CURLOPT_TIMEOUT,60);
            $_data = curl_exec($hander);
            curl_close($hander);
            file_write($_filename,$_data);
        }
        return tomedia($_filename);
    }
}